<?php
/*
# $Id: Config.php 10 2006-11-18 12:34:32Z James $
*/

/*
# @class Config
*/
class Config {

	/*
	# @property array $var
	# Directive storage array. Separates config namespaces using hash keys.
	*/
	static protected $var = array();

	/*
	# @property array $_getCache
	# Stores an in-memory cache of the results of all calls to Config::get().
	*/
	static protected $_getCache = array();

	/*
	# @method array createNamespace( string $namespace )
	# $namespace	= Namespace (dot-separated)
	#
	# Creates the specified namespace tree and returns a reference to it.
	*/
	static public function createNamespace($namespace) {

		// Create all specified namespace nodes
		return eval("return self::\$var['".str_replace('.', "']['", $namespace)."'] = array();");
	}

	/*
	# @method bool is_set( string $path )
	# $path	= Config path
	#
	# Returns TRUE if the specified config variable has been set.
	*/
	static public function is_set($path) {
		$arrayPath = is_null($path) ? '' : "['".implode("']['", explode(".", $path))."']";
		eval('$isset = isset(self::$var'.$arrayPath.') ? TRUE : FALSE;');
		return $isset;
	}

	/*
	# @method bool set( string $varName, mixed $varValue )
	# $varName	= Variable path (dot-separated)
	# $varValue	= Value to store
	#
	# Sets the specified config variable.
	# $varName may be a namespace path, eg. "path.to.namespace.variable"
	*/
	static public function set($varName, $varValue) {

		// Separate the namespace from the given variable name
		$lastDot = strrpos($varName, '.');
		if($lastDot===FALSE) {
			self::$var[$varName] = $varValue;
			return TRUE;
		}
		$namespace = substr($varName, 0, $lastDot);
		$varName = substr($varName, $lastDot+1);

		// Get a reference to the namespace's tree
		$arrayPath = "['".str_replace('.', "']['", $namespace)."']";
		eval('$ns =& self::$var'.$arrayPath.';');
		if($ns===NULL) {

			// Create namespace
			$ns = self::createNamespace($namespace);
		}

		// Clear cache
		self::$_getCache = array();

		// Set the variable
		$ns[$varName] = self::$_getCache["{$namespace}.{$varName}"] = $varValue;
		return TRUE;
	}

	/*
	# @method mixed get( [string $path] )
	# $path	= Config variable path (dot-separated)
	#
	# Returns a config variable or a namespace tree
	*/
	static public function get($path=NULL) {

		// Check memory cache first
		if(isset(self::$_getCache[$path])) return self::$_getCache[$path];

		// Find and return the specified variable/namespace tree
		$arrayPath = $path===NULL ? '' : "['".str_replace('.', "']['", $path)."']";
		return eval('return isset(self::$var'.$arrayPath.') ? self::$_getCache[$path] = self::$var'.$arrayPath.' : NULL;');
	}
}
?>